package cn.tedu.micro.service.order.service.impl;

import cn.tedu.micro.service.order.mapper.OrderMapper;
import cn.tedu.micro.service.order.openfeign.client.CartClient;
import cn.tedu.micro.service.order.openfeign.client.StockClient;
import cn.tedu.micro.service.order.service.OrderService;
import cn.tedu.micro.service.pojo.param.OrderAddParam;
import cn.tedu.micro.service.pojo.po.OrderPO;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class OrderServiceImpl  implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private StockClient stockClient;
    @Autowired
    private CartClient cartClient;

//    @GlobalTransactional
    @Override
    public Boolean addOrder(OrderAddParam orderAddParam) {
        //新增订单入库之前-减少库存(是否充足)-删除购物车(对应用户的对应商品)
        //1.减少库存数
        stockClient.reduceStock(orderAddParam.getProductCode(),orderAddParam.getCount());
        //2.删除购物中的商品
        cartClient.deleteCart(orderAddParam.getProductCode(),orderAddParam.getUserId());
        //3.新增订单到数据库中
        OrderPO orderPO = new OrderPO();
        BeanUtils.copyProperties(orderAddParam,orderPO);
        orderPO.setOrderSn((new Date()).toString());
        int orderResult = orderMapper.insert(orderPO);
        //为了验证分布式事务效果，随机抛出异常
        if(Math.random()<0.6){
            System.out.println(1/0);
        }
        if(!(orderResult>=1))
            return false;
        return true;
    }
}
